package com.zm.demo.core.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

import static java.lang.System.out;

/**
 * @author zoum
 * @create 2019/10/12 15:27
 */
public class ReentrantLockDemo {

    public static void main(String[] args) throws Exception{
        noReentrent();
    }

    private static void reentrent(){
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        try {
            out.println(Thread.currentThread().getName() + "第一次获取锁...");
            lock.lock();
            try {
                out.println(Thread.currentThread().getName() + "重入...");

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                out.println(Thread.currentThread().getName() + "重入释放...");
                lock.unlock();
            }
        }finally {
            out.println(Thread.currentThread().getName() + "第一次释放锁...");
            lock.unlock();
        }
    }

    private static void noReentrent() throws Exception{
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        try {
            out.println(Thread.currentThread().getName() + "第一次获取锁...");

            ExecutorService pool = Executors.newCachedThreadPool();
            pool.submit(() ->{
                lock.lock();
                try {
                    out.println(Thread.currentThread().getName() + "其他线程获取锁...");

                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    out.println(Thread.currentThread().getName() + "其他线程释放锁...");
                    lock.unlock();
                }
            });

            for (; ; ) {

            }
//            Thread.sleep(1000L);
//            pool.shutdown();
        }finally {
            out.println(Thread.currentThread().getName() + "第一次释放锁...");
            lock.unlock();
        }
    }
}
